<template>
  <div class="detail-management-container">
    <header class="detail-header">
      <h2>类别管理</h2>
    </header>
    
    <!-- 消息提示 -->
    <div v-if="message" class="message" :class="{ 'success': messageType === 'success', 'error': messageType === 'error' }">
      {{ message }}
    </div>
    
    <!-- 二级导航栏 -->
    <nav class="sub-nav">
      <ul class="sub-nav-list">
        <li class="sub-nav-item" :class="{ active: currentSubMenu === 'doctor' }">
          <a href="#" @click.prevent="selectSubMenu('doctor')">医师</a>
        </li>
        <li class="sub-nav-item" :class="{ active: currentSubMenu === 'company' }">
          <a href="#" @click.prevent="selectSubMenu('company')">公司</a>
        </li>
        <li class="sub-nav-item" :class="{ active: currentSubMenu === 'medicine' }">
          <a href="#" @click.prevent="selectSubMenu('medicine')">药品</a>
        </li>
      </ul>
    </nav>
    
    <!-- 医师页面 -->
    <div v-if="currentSubMenu === 'doctor'" class="detail-section">
      <h3>诊治类别管理</h3>
      <div class="add-bar">
        <el-input v-model="newCategory" placeholder="新增诊治类别" class="detail-input" size="large" style="max-width:220px;" />
        <el-button type="primary" size="large" @click="addCategory" :loading="loading">{{ loading ? '添加中...' : '添加' }}</el-button>
      </div>
      <ul class="detail-list">
        <li v-for="(item, idx) in doctorCategories" :key="item.id" class="detail-list-item">
          <span class="category-text">{{ item.category }}</span>
          <el-button type="danger" size="large" @click="deleteCategory(item.id)">删除</el-button>
        </li>
      </ul>
    </div>

    <!-- 公司页面 -->
    <div v-if="currentSubMenu === 'company'" class="detail-section">
      <h3>公司类别管理</h3>
      <div class="add-bar">
        <el-input v-model="newCompanyCategory" placeholder="新增公司类别" class="detail-input" size="large" style="max-width:220px;" />
        <el-button type="primary" size="large" @click="addCompanyCategoryItem">添加</el-button>
      </div>
      <ul class="detail-list">
        <li v-for="(item, idx) in companyCategories" :key="item.id" class="detail-list-item">
          <span class="category-text">{{ item.category }}</span>
          <el-button type="danger" size="large" @click="deleteCompanyCategory(item.id)">删除</el-button>
        </li>
      </ul>
    </div>

    <!-- 药品页面 -->
    <div v-if="currentSubMenu === 'medicine'" class="detail-section">
      <h3>药品类别管理</h3>
      <div class="add-bar">
        <el-input v-model="newMedicineCategory" placeholder="新增药品类别" class="detail-input" size="large" style="max-width:220px;" />
        <el-button type="primary" size="large" @click="addMedicineCategoryItem">添加</el-button>
      </div>
      <ul class="detail-list">
        <li v-for="(item, idx) in medicineCategories" :key="item.id" class="detail-list-item">
          <span class="category-text">{{ item.category }}</span>
          <el-button type="danger" size="large" @click="deleteMedicineCategory(item.id)">删除</el-button>
        </li>
      </ul>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';

const props = defineProps({
  currentSubMenu: {
    type: String,
    default: 'doctor'
  }
});

const emit = defineEmits(['update:currentSubMenu']);

// 消息提示
const message = ref('');
const messageType = ref('');
const loading = ref(false);

// 显示消息提示
function showMessage(msg, type = 'success') {
  message.value = msg;
  messageType.value = type;
  setTimeout(() => {
    message.value = '';
    messageType.value = '';
  }, 3000);
}

// 医师相关数据
const doctorCategories = ref([]);
// 公司相关数据
const companyCategories = ref([]);
// 药品相关数据
const medicineCategories = ref([]);

// 获取所有类别
async function fetchDoctorCategories() {
  try {
    loading.value = true;
    const storedToken = localStorage.getItem('token');
    const response = await axios.get('http://47.93.134.56:8800/doctor/get/categories', {
      headers: { 'token': storedToken }
    });
    if (response.data.code === 200) {
      doctorCategories.value = response.data.data;
    } else {
      showMessage(response.data.msg || '获取医生类别失败', 'error');
    }
  } catch (error) {
    showMessage(error.response?.data?.msg || '网络错误', 'error');
  } finally {
    loading.value = false;
  }
}
async function fetchCompanyCategories() {
  try {
    loading.value = true;
    const storedToken = localStorage.getItem('token');
    const response = await axios.get('http://47.93.134.56:8800/company/get/categories', {
      headers: { 'token': storedToken }
    });
    if (response.data.code === 200) {
      companyCategories.value = response.data.data;
    } else {
      showMessage(response.data.msg || '获取公司类别失败', 'error');
    }
  } catch (error) {
    showMessage(error.response?.data?.msg || '网络错误', 'error');
  } finally {
    loading.value = false;
  }
}
async function fetchMedicineCategories() {
  try {
    loading.value = true;
    const storedToken = localStorage.getItem('token');
    const response = await axios.get('http://47.93.134.56:8800/medical/get/categories', {
      headers: { 'token': storedToken }
    });
    if (response.data.code === 200) {
      medicineCategories.value = response.data.data;
    } else {
      showMessage(response.data.msg || '获取药品类别失败', 'error');
    }
  } catch (error) {
    showMessage(error.response?.data?.msg || '网络错误', 'error');
  } finally {
    loading.value = false;
  }
}

// 医师诊治类别编辑
const newCategory = ref('');
const editCategoryIdx = ref(-1);
const editCategoryValue = ref('');
async function addCategory() {
  if (!newCategory.value) {
    showMessage('请输入类别名称', 'error');
    return;
  }
  
  if (doctorCategories.value.some(item => item.category === newCategory.value)) {
    showMessage('该类别已存在', 'error');
    return;
  }
  
  const success = await addDoctorCategory(newCategory.value);
  if (success) {
    newCategory.value = '';
    updateLocalStorage();
  }
}
async function deleteCategory(id) {
  if (confirm('确定要删除该诊治类别吗？')) {
    const success = await deleteDoctorCategoryById(id);
    if (success) {
      doctorCategories.value = doctorCategories.value.filter(item => item.id !== id);
      updateLocalStorage();
    }
  }
}
function startEditCategory(idx, val) {
  editCategoryIdx.value = idx;
  editCategoryValue.value = val;
}
function saveEditCategory(idx) {
  if (editCategoryValue.value && !doctorCategories.value.some(item => item.category === editCategoryValue.value)) {
    doctorCategories.value[idx].category = editCategoryValue.value;
    editCategoryIdx.value = -1;
    editCategoryValue.value = '';
    updateLocalStorage();
  }
}
function cancelEditCategory() {
  editCategoryIdx.value = -1;
  editCategoryValue.value = '';
}

// 公司类别编辑
const newCompanyCategory = ref('');
const editCompanyCategoryIdx = ref(-1);
const editCompanyCategoryValue = ref('');
async function addCompanyCategoryItem() {
  if (!newCompanyCategory.value) {
    showMessage('请输入类别名称', 'error');
    return;
  }
  
  if (companyCategories.value.some(item => item.category === newCompanyCategory.value)) {
    showMessage('该类别已存在', 'error');
    return;
  }
  
  const success = await addCompanyCategory(newCompanyCategory.value);
  if (success) {
    newCompanyCategory.value = '';
    updateLocalStorage();
  }
}
async function deleteCompanyCategory(id) {
  if (confirm('确定要删除该公司类别吗？')) {
    const success = await deleteCompanyCategoryById(id);
    if (success) {
      companyCategories.value = companyCategories.value.filter(item => item.id !== id);
      updateLocalStorage();
    }
  }
}
function startEditCompanyCategory(idx, val) {
  editCompanyCategoryIdx.value = idx;
  editCompanyCategoryValue.value = val;
}
function saveEditCompanyCategory(idx) {
  if (editCompanyCategoryValue.value && !companyCategories.value.some(item => item.category === editCompanyCategoryValue.value)) {
    companyCategories.value[idx].category = editCompanyCategoryValue.value;
    editCompanyCategoryIdx.value = -1;
    editCompanyCategoryValue.value = '';
    updateLocalStorage();
  }
}
function cancelEditCompanyCategory() {
  editCompanyCategoryIdx.value = -1;
  editCompanyCategoryValue.value = '';
}

// 药品类别编辑
const newMedicineCategory = ref('');
const editMedicineCategoryIdx = ref(-1);
const editMedicineCategoryValue = ref('');
async function addMedicineCategoryItem() {
  if (!newMedicineCategory.value) {
    showMessage('请输入类别名称', 'error');
    return;
  }
  
  if (medicineCategories.value.some(item => item.category === newMedicineCategory.value)) {
    showMessage('该类别已存在', 'error');
    return;
  }
  
  const success = await addMedicineCategory(newMedicineCategory.value);
  if (success) {
    newMedicineCategory.value = '';
    updateLocalStorage();
  }
}
async function deleteMedicineCategory(id) {
  if (confirm('确定要删除该药品类别吗？')) {
    const success = await deleteMedicineCategoryById(id);
    if (success) {
      medicineCategories.value = medicineCategories.value.filter(item => item.id !== id);
      updateLocalStorage();
    }
  }
}
function startEditMedicineCategory(idx, val) {
  editMedicineCategoryIdx.value = idx;
  editMedicineCategoryValue.value = val;
}
function saveEditMedicineCategory(idx) {
  if (editMedicineCategoryValue.value && !medicineCategories.value.some(item => item.category === editMedicineCategoryValue.value)) {
    medicineCategories.value[idx].category = editMedicineCategoryValue.value;
    editMedicineCategoryIdx.value = -1;
    editMedicineCategoryValue.value = '';
    updateLocalStorage();
  }
}
function cancelEditMedicineCategory() {
  editMedicineCategoryIdx.value = -1;
  editMedicineCategoryValue.value = '';
}

// 数据持久化和联动
function updateLocalStorage() {
  localStorage.setItem('doctorCategories', JSON.stringify(doctorCategories.value));
  localStorage.setItem('companyCategories', JSON.stringify(companyCategories.value));
  localStorage.setItem('medicineCategories', JSON.stringify(medicineCategories.value));
}

// 添加医生类别
async function addDoctorCategory(categoryName) {
  try {
    loading.value = true;
    const storedToken = localStorage.getItem('token');
    const response = await axios.post('http://47.93.134.56:8800/doctor/add/category', { category: categoryName }, {
      headers: { 'token': storedToken }
    });
    if (response.data.code === 200) {
      showMessage(response.data.msg || '添加医生类别成功');
      doctorCategories.value.push(response.data.data);
      return true;
    } else {
      showMessage(response.data.msg || '添加医生类别失败', 'error');
      return false;
    }
  } catch (error) {
    showMessage(error.response?.data?.msg || '网络错误', 'error');
    return false;
  } finally {
    loading.value = false;
  }
}
// 删除医生类别
async function deleteDoctorCategoryById(id) {
  try {
    loading.value = true;
    const storedToken = localStorage.getItem('token');
    const response = await axios.delete(`http://47.93.134.56:8800/doctor/delete/category/${id}`, {
      headers: { 'token': storedToken }
    });
    if (response.data.code === 200) {
      showMessage(response.data.msg || '删除医生类别成功');
      doctorCategories.value = doctorCategories.value.filter(item => item.id !== id);
      return true;
    } else {
      showMessage(response.data.msg || '删除医生类别失败', 'error');
      return false;
    }
  } catch (error) {
    showMessage(error.response?.data?.msg || '网络错误', 'error');
    return false;
  } finally {
    loading.value = false;
  }
}
// 添加公司类别
async function addCompanyCategory(categoryName) {
  try {
    loading.value = true;
    const storedToken = localStorage.getItem('token');
    const response = await axios.post('http://47.93.134.56:8800/company/add/category', { category: categoryName }, {
      headers: { 'token': storedToken }
    });
    if (response.data.code === 200) {
      showMessage(response.data.msg || '添加公司类别成功');
      companyCategories.value.push(response.data.data);
      return true;
    } else {
      showMessage(response.data.msg || '添加公司类别失败', 'error');
      return false;
    }
  } catch (error) {
    showMessage(error.response?.data?.msg || '网络错误', 'error');
    return false;
  } finally {
    loading.value = false;
  }
}
// 删除公司类别
async function deleteCompanyCategoryById(id) {
  try {
    loading.value = true;
    const storedToken = localStorage.getItem('token');
    const response = await axios.delete(`http://47.93.134.56:8800/company/delete/category/${id}`, {
      headers: { 'token': storedToken }
    });
    if (response.data.code === 200) {
      showMessage(response.data.msg || '删除公司类别成功');
      companyCategories.value = companyCategories.value.filter(item => item.id !== id);
      return true;
    } else {
      showMessage(response.data.msg || '删除公司类别失败', 'error');
      return false;
    }
  } catch (error) {
    showMessage(error.response?.data?.msg || '网络错误', 'error');
    return false;
  } finally {
    loading.value = false;
  }
}
// 添加药品类别
async function addMedicineCategory(categoryName) {
  try {
    loading.value = true;
    const storedToken = localStorage.getItem('token');
    const response = await axios.post('http://47.93.134.56:8800/medical/add/category', { category: categoryName }, {
      headers: { 'token': storedToken }
    });
    if (response.data.code === 200) {
      showMessage(response.data.msg || '添加药品类别成功');
      medicineCategories.value.push(response.data.data);
      return true;
    } else {
      showMessage(response.data.msg || '添加药品类别失败', 'error');
      return false;
    }
  } catch (error) {
    showMessage(error.response?.data?.msg || '网络错误', 'error');
    return false;
  } finally {
    loading.value = false;
  }
}
// 删除药品类别
async function deleteMedicineCategoryById(id) {
  try {
    loading.value = true;
    const storedToken = localStorage.getItem('token');
    const response = await axios.delete(`http://47.93.134.56:8800/medical/delete/category/${id}`, {
      headers: { 'token': storedToken }
    });
    if (response.data.code === 200) {
      showMessage(response.data.msg || '删除药品类别成功');
      medicineCategories.value = medicineCategories.value.filter(item => item.id !== id);
      return true;
    } else {
      showMessage(response.data.msg || '删除药品类别失败', 'error');
      return false;
    }
  } catch (error) {
    showMessage(error.response?.data?.msg || '网络错误', 'error');
    return false;
  } finally {
    loading.value = false;
  }
}

function selectSubMenu(subMenu) {
  emit('update:currentSubMenu', subMenu);
}

onMounted(() => {
  fetchDoctorCategories();
  fetchCompanyCategories();
  fetchMedicineCategories();
});
</script>

<style scoped>
.detail-management-container {
  background: #fff;
  border-radius: 10px;
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
  box-shadow: 0 2px 8px rgba(0,0,0,0.08);
  overflow: hidden;
}

/* 消息提示样式 */
.message {
  padding: 12px 16px;
  margin-bottom: 15px;
  border-radius: 6px;
  font-size: 0.9rem;
  font-weight: 500;
}

.message.success {
  background: #d4edda;
  color: #155724;
  border: 1px solid #c3e6cb;
}

.message.error {
  background: #f8d7da;
  color: #721c24;
  border: 1px solid #f5c6cb;
}

.detail-header {
  margin-bottom: 20px;
}

/* 二级导航栏样式 */
.sub-nav {
  margin-bottom: 30px;
  border-bottom: 1px solid #e0e0e0;
}

.sub-nav-list {
  list-style: none;
  padding: 0;
  margin: 0;
  display: flex;
  gap: 0;
}

.sub-nav-item {
  position: relative;
}

.sub-nav-item a {
  display: block;
  padding: 15px 25px;
  color: #666;
  text-decoration: none;
  font-weight: 500;
  transition: all 0.3s ease;
  border-bottom: 3px solid transparent;
}

.sub-nav-item a:hover {
  color: #333;
  background-color: #f8f9fa;
}

.sub-nav-item.active a {
  color: #3498db;
  border-bottom-color: #3498db;
  background-color: #f8f9fa;
}

.sub-nav-item.active::after {
  content: '';
  position: absolute;
  bottom: -1px;
  left: 0;
  right: 0;
  height: 1px;
  background-color: #fff;
}

.detail-section {
  margin-bottom: 32px;
  flex: 1;
  overflow-y: auto;
}

.detail-list {
  display: flex;
  flex-wrap: wrap;
  gap: 18px 2%;
  margin-top: 16px;
}

.detail-list-item {
  width: 32%;
  min-width: 220px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #f9f9f9;
  padding: 18px 24px;
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.04);
}

.category-text {
  flex: 1;
  text-align: left;
  font-size: 1.25rem;
  color: #222;
  font-weight: 600;
  letter-spacing: 1px;
}

.add-bar {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 10px;
}

.detail-input {
  padding: 4px 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
  font-size: 1rem;
}

.detail-list button, .add-bar button {
  background: #3498db;
  color: #fff;
  border: none;
  padding: 4px 10px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.95rem;
}

.detail-list button:hover, .add-bar button:hover {
  background: #217dbb;
}

/* 删除按钮样式 */
.detail-list-item .el-button[type~="danger"],
.detail-list button {
  background-color: #f8d7da;
  color: #721c24;
  border: 1px solid #f5c6cb;
}
.detail-list-item .el-button[type~="danger"]:hover,
.detail-list button:hover {
  background-color: #f5c6cb;
  color: #721c24;
}

/* 禁用状态 */
.add-bar button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .sub-nav-list {
    flex-direction: column;
  }
  
  .sub-nav-item a {
    padding: 12px 20px;
    text-align: center;
  }
  
  .detail-list li {
    width: 100%;
  }
}
</style>